package com.library.web.user;

import com.library.dao.UserDAO;
import com.library.model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private final UserDAO userDao = new UserDAO();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String remember = req.getParameter("remember");
        String redirect = req.getParameter("redirect");
        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty()) {
            req.setAttribute("error", "用户名和密码不能为空");
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
            return;
        }

        User loginUser = userDao.getUserByUsernameAndPassword(username, password);

        if (loginUser != null) {
            if ("on".equals(remember)) {
                // 对用户名和密码进行简单加密（避免明文存储）
                String encodeUsername = URLEncoder.encode(username, "UTF-8");
                String encodePassword = URLEncoder.encode(password, "UTF-8");
                Cookie cUsername = new Cookie("username", encodeUsername);
                Cookie cPassword = new Cookie("password", encodePassword);
                // 设置Cookie路径（仅当前项目可访问）
                cUsername.setPath(req.getContextPath() + "/");
                cPassword.setPath(req.getContextPath() + "/");
                // 设置有效期30天
                cUsername.setMaxAge(30 * 24 * 60 * 60);
                cPassword.setMaxAge(30 * 24 * 60 * 60);
                resp.addCookie(cUsername);
                resp.addCookie(cPassword);
            } else {
                // 未勾选"记住我"，清除原有Cookie
                clearLoginCookies(req, resp);
            }
            HttpSession session = req.getSession();
            // 移除旧的登录信息（避免Session污染）
            session.removeAttribute("user");
            // 存储用户信息（建议只存必要字段，而非完整User对象）
            session.setAttribute("user", loginUser);
            // 设置Session有效期（30分钟）
            session.setMaxInactiveInterval(30 * 60);
            resp.sendRedirect(req.getContextPath() + "/home?action=page");

        } else {
            req.setAttribute("error", "账号或密码错误");
            req.setAttribute("username", username);
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
        }
    }

    private void clearLoginCookies(HttpServletRequest req, HttpServletResponse resp) {
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName()) || "password".equals(cookie.getName())) {
                    cookie.setValue("");
                    cookie.setMaxAge(0); // 立即失效
                    cookie.setPath(req.getContextPath() + "/");
                    resp.addCookie(cookie);
                }
            }
        }
    }
}
